package ru.kest.torrentwatchlist.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.kest.torrentwatchlist.dao.MovieDAO;
import ru.kest.torrentwatchlist.entity.Movie;
import ru.kest.torrentwatchlist.parsing.ParsingService;
import ru.kest.torrentwatchlist.web.model.MovieBean;
import ru.kest.torrentwatchlist.web.transform.MoviesTransformer;

import java.util.Collection;
import java.util.List;

/**
 * Created by kkharitonov on 16.11.2014.
 */
@RestController
public class TorrentsListController {

    @Autowired
    private MovieDAO movieDAO;

    @Autowired
    private ParsingService parsingService;

    @Autowired
    MoviesTransformer moviesTransformer;

    private static Logger logger = Logger.getLogger(TorrentsListController.class);

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public
    @ResponseBody
    String test() {

        return "Test answer";
    }


    @RequestMapping(value = "/removeAll", method = RequestMethod.GET)
    public
    @ResponseBody
    String removeAll() {

        parsingService.removeAll();
        return "Test answer";
    }

    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public
    @ResponseBody
    String start() {

        int newMovies = parsingService.parseAll();
        return "Added " + newMovies + " new movies";
    }

    @RequestMapping(value = "/movies", method = RequestMethod.GET)
    public
    @ResponseBody
    List<MovieBean> getAllMovies() {

        List<Movie> movies = movieDAO.findAllMovies();
        return moviesTransformer.transformMovies(movies);
    }

    @RequestMapping(value = "/movies", method = {RequestMethod.POST, RequestMethod.PUT})
    @ResponseStatus(value = HttpStatus.OK)
    public void updateMovies(@RequestBody Collection<MovieBean> movies) {

        for(MovieBean movie : movies) {
            logger.info(movie);
            if (movie.isFavorites() != null) {
                movieDAO.setFavorites(movie.getId(), movie.isFavorites());
            }
        }
    }

    @RequestMapping(value = "/skip", method = {RequestMethod.POST, RequestMethod.PUT})
    @ResponseStatus(value = HttpStatus.OK)
    public void skipMovies(@RequestBody Collection<Integer> idsToSkip) {

        for(Integer id : idsToSkip) {
            logger.info("Id to skip: " + id);
            movieDAO.setSkipped(id);
        }
    }


}
